import sha1 from "sha1";
import getRawBody from "raw-body";
import { parmsXml,formatMessage } from "./utils";
import reply from "../wechat/reply"

export const middlewareWechat = config => async (ctx, next) => {
  const { wechat: { token } } = config;
  const { signature, timestamp, nonce, echostr } = ctx.query;

  const str = [token, timestamp, nonce].sort().join("");
  const sha = sha1(str);
  console.log(sha === signature);
  if (ctx.method === "GET") {
    if (sha === signature) {
      ctx.body = echostr;
    } else {
      ctx.body = "Failed";
    }
  } else if (ctx.method === "POST") {
    if (sha !== signature) {
      return false;
    }
    // 设置获取信息规则
    const message = await getRawBody(ctx.req, {
      length: ctx.length,
      limit: "1mb",
      encoding: ctx.charset
    });
    // 解析
    const msgRes = await parmsXml(message);
    const msgJson = formatMessage(msgRes.xml); 
    ctx.msgJson = msgJson;
    const myReply = await reply(ctx,next);
    ctx.status = 200;
    ctx.type = "application/xml";
    ctx.body = myReply;
  }
};
